/**
 * Request Mock数据
 * 简单的mock数据管理
 */

// 扩展Error类型以支持mockData属性
declare global {
  interface Error {
    mockData?: any;
  }
}

// Mock开关 - 改为false关闭
const ENABLE_MOCK = true;

// Mock处理器 - 统一处理mock逻辑
export const handleMockRequest = (config: any) => {
  if (!ENABLE_MOCK) return;
  if (!config.url) return;

  // 仅当显式以 /mock 开头时启用 mock
  if (!/^\/mock(\/|$)/.test(config.url)) return;

  // 去掉 /mock 前缀用于匹配具体业务路径
  const requestPath = config.url.replace(/^\/mock/, "") || "/";
  const method = (config.method || "GET").toUpperCase();

  const matched = ROUTES.find((r) => r.test(requestPath, method));
  if (!matched) return;

  console.log("[MOCK]", method, requestPath, { params: config.params, data: config.data });
  const data = matched.respond(config, requestPath, method);
  throwMockResponse(config, data);
};

// Mock响应生成器
const createMockResponse = (data: any, config: any) => {
  return {
    status: 200,
    statusText: "OK",
    data: {
      code: 200,
      data: data,
    },
    config: config,
    headers: {},
  };
};

// ------- 抽离的类型与工具 -------
type MockRoute = {
  test: (path: string, method: string) => boolean;
  respond: (config: any, path: string, method: string) => any;
};

const throwMockResponse = (config: any, data: any) => {
  const mockError = new Error("MOCK_RESPONSE");
  mockError.mockData = createMockResponse(data, config);
  throw mockError;
};

const ROUTES: MockRoute[] = [];

// 动态注册mock路由：method('*'表示任意方法)，path可为字符串或正则
export const mock = (method: string, path: string | RegExp, dataCallback: (config: any) => any) => {
  const upperMethod = (method || "GET").toUpperCase();
  ROUTES.push({
    test: (requestPath, requestMethod) => {
      const methodMatched = upperMethod === "*" || requestMethod === upperMethod;
      const pathMatched =
        path instanceof RegExp ? (path as RegExp).test(requestPath) : requestPath.includes(path as string);
      return methodMatched && pathMatched;
    },
    respond: (config) => dataCallback(config),
  });
};

// 公用便捷数据生成器
export const ok = () => ({ success: true });
